import { FC, useCallback, useEffect, useMemo, useState } from 'react';
import { Badge, DatePicker, Input, Space, Switch } from 'antd';
import { isArray, isNil } from 'lodash';
import { observer } from 'mobx-react';

import RbProTable, { RbProTableStore } from '@components/RbProTable';
import { Content } from '@components/Page';
import Button from '@/components/Button';

import { COMMON_REQUIRE_RULE } from '@utils/config';
import { Status } from '@enumTypes/enumTypes';
import {
  generateCommonDeleteModal,
  generateCommonSelect,
  setOtherTypeValue
} from '@utils/renderer';
import { getDictionaryListApi } from '@services/service';
import { TableAlignType } from '@/enumTypes/table';
import request from '@/utils/request';
import notification from '@/utils/notification';

const store = new RbProTableStore();

const UserSetting: FC = () => {
  // 字典数据
  const [statusList, setStatusList] = useState<any[]>([]);

  /** 查询设置字典数据 */
  const handleQueryDictionaryList = useCallback(() => {
    getDictionaryListApi(['RB_STATUS']).then((res: any) => {
      if (isArray(res)) {
        const [statusList = []] = res || [];
        setStatusList(statusList);
      }
    });
  }, []);

  useEffect(() => {
    handleQueryDictionaryList();
  }, []);

  /** 重置密码 用户界面存在 */
  const handleResetPwd = useCallback(() => {
    if (!store.selectedKeys.length) return;

    generateCommonDeleteModal({
      title: '是否重置密码？',
      onOk() {
        store.setLoading(true);
        request({
          url: '/system/user/reset',
          method: 'POST',
          data: store.selectedKeys
        })
          .then(async (res: any) => {
            if (res) {
              notification.success();
              await store.query();
            }
          })
          .finally(() => {
            store.setLoading(false);
          });
      }
    });
  }, []);

  /** 查询条配置列表 */
  const queryFromItems = useMemo(
    () => [
      {
        name: 'username',
        label: '用户名',
        children: <Input />
      },
      {
        name: 'nickname',
        label: '昵称',
        children: <Input />
      },
      {
        name: 'status',
        label: '状态',
        children: generateCommonSelect(statusList)
      },
      {
        name: 'createTime',
        label: '创建日期',
        children: <DatePicker.RangePicker showTime />
      }
    ],
    [statusList]
  );

  /** 表格列配置 */
  const columns = useMemo(
    () => [
      {
        title: '用户名',
        dataIndex: 'username',
        align: TableAlignType.center,
        width: 140
      },
      {
        title: '昵称',
        dataIndex: 'nickname',
        align: TableAlignType.center,
        width: 140
      },
      {
        title: '状态',
        dataIndex: 'status',
        align: TableAlignType.center,
        render: (value: any) => {
          return (
            !isNil(value) && (
              <Space>
                <Badge status={Status.enable === value ? 'success' : 'error'} />
                {value === 1 ? '启用' : value === 0 ? '禁用' : ''}
              </Space>
            )
          );
        },
        width: 120
      },
      {
        title: '手机',
        dataIndex: 'phone',
        align: TableAlignType.center,
        width: 140
      },
      {
        title: '邮箱',
        dataIndex: 'email',
        align: TableAlignType.center,
        width: 180
      },
      {
        title: '创建人',
        dataIndex: 'createBy',
        align: TableAlignType.center,
        sorter: true,
        width: 140
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        align: TableAlignType.center,
        sorter: true,
        width: 180
      },
      {
        title: '备注',
        dataIndex: 'remark',
        ellipsis: true,
        width: 280
      }
    ],
    []
  );

  /** 新增表单配置 */
  const addFormItems = useMemo(
    () => [
      {
        name: 'username',
        label: '用户名',
        rules: [COMMON_REQUIRE_RULE],
        children: <Input />
      },
      {
        name: 'nickname',
        label: '昵称',
        rules: [COMMON_REQUIRE_RULE],
        children: <Input />
      },
      {
        name: 'status',
        label: '状态',
        rules: [COMMON_REQUIRE_RULE],
        ...setOtherTypeValue(1, 0),
        valuePropName: 'checked',
        children: <Switch checkedChildren="启用" unCheckedChildren="禁用" />
      },
      //TODO 这个等做文件上传后再来修改
      {
        name: 'avatar',
        label: '头像地址',
        // rules: [COMMON_REQUIRE_RULE],
        children: <Input />
      },
      {
        name: 'phone',
        label: '手机',
        children: <Input />
      },
      {
        name: 'email',
        label: '邮件',
        children: <Input />
      },
      {
        name: 'remark',
        label: '备注',
        children: <Input.TextArea />
      }
    ],
    []
  );

  /** 编辑表单配置 */
  const updateFormItems = useMemo(
    () => [
      {
        name: 'username',
        label: '用户名',
        rules: [COMMON_REQUIRE_RULE],
        children: <Input />
      },
      {
        name: 'nickname',
        label: '昵称',
        rules: [COMMON_REQUIRE_RULE],
        children: <Input />
      },
      {
        name: 'status',
        label: '状态',
        rules: [COMMON_REQUIRE_RULE],
        ...setOtherTypeValue(1, 0),
        valuePropName: 'checked',
        children: <Switch checkedChildren="启用" unCheckedChildren="禁用" />
      },
      //TODO 这个等做文件上传后再来修改
      {
        name: 'avatar',
        label: '头像地址',
        // rules: [COMMON_REQUIRE_RULE],
        children: <Input />
      },
      {
        name: 'phone',
        label: '手机',
        children: <Input />
      },
      {
        name: 'email',
        label: '邮件',
        children: <Input />
      },
      {
        name: 'remark',
        label: '备注',
        children: <Input.TextArea />
      }
    ],
    []
  );

  return (
    <Content>
      <RbProTable
        rowKey="id"
        columns={columns}
        store={store}
        actionUrl="/system/user"
        sticky
        selectionType
        queryConfig={{
          queryFromItems,
          queryFormat: true,
          queryInitialValues: { status: 1 }
        }}
        addConfig={{
          addFormItems,
          addInitialValues: { status: 1 }
        }}
        updateConfig={{ updateFormItems }}
        toolBarRender={() => [
          'add',
          'update',
          'delete',
          <Button
            key="resetPwd"
            type="primary"
            disabled={!store.selected.length}
            onClick={() => handleResetPwd()}
          >
            重置密码
          </Button>
        ]}
      />
    </Content>
  );
};

export default observer(UserSetting);
